package wsdc.app.main;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.time.format.DateTimeFormatter;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;

/*
 *  context对象
 *  全局的上下文对象
 *  -   web请求使用
 *  -   内部线程池使用
 *
 *  -   提供context
 */
@Component
@Slf4j
@Getter
public class SpringContext implements ApplicationContextAware {
    static List<Consumer<ApplicationContext>> consumerList = new LinkedList<>();

    static ApplicationContext context;

    public static ApplicationContext context() {
        return context;
    }

    public SpringContext() {
        instance = this;
    }

    private static SpringContext instance;

    public static SpringContext getInstance() {
        return instance;
    }

    //  定义一个线程池


    public static void register(Consumer<ApplicationContext> consumer) {
        if (context != null) {
            consumer.accept(context);
        } else {
            consumerList.add(consumer);
        }
    }

    public static void unregister(Consumer<ApplicationContext> consumer) {
        consumerList.remove(consumer);
    }

    private static void active() {
        consumerList.stream().forEach(item -> {
            item.accept(context);
        });
        //  清空消费者   这个方法只会调用一次
        consumerList.clear();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
        active();
    }

}
